package pkg

import (
	"fmt"
	rotate "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"path"
	"time"
)

var Logger *logrus.Logger

func InitLogSetup() {
	logInfo := initLogFileInfo()

	// 使日志记录支持日志切割，日志轮转并清洗
	handler, err := rotate.New(
		// 分割后的文件名称
		logInfo.createSavePath()+".%Y%m%d"+logInfo.Ext,
		// 生成软链，指向最新日志文件
		rotate.WithLinkName(logInfo.createSavePath()),
		// 设置最大保存时间(7天)
		rotate.WithMaxAge(7*24*time.Hour),
		// 设置日志切割时间间隔(1天)
		rotate.WithRotationTime(24*time.Hour),
	)
	if err != nil {
		fmt.Printf("日志失败，Err:%s\n", err.Error())
	}
	logrus.AddHook(lfshook.NewHook(
		lfshook.WriterMap{
			logrus.InfoLevel:  handler,
			logrus.ErrorLevel: handler,
			logrus.FatalLevel: handler,
			logrus.DebugLevel: handler,
			logrus.WarnLevel:  handler,
			logrus.PanicLevel: handler,
			logrus.TraceLevel: handler,
		},
		&logrus.JSONFormatter{
			TimestampFormat: logInfo.TimeFormat,
		},
	))

	Logger = logrus.New()
	Logger.Out = handler
	Logger.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat:   logInfo.TimeFormat,
		DisableHTMLEscape: true,
	})

	// 输出日志中添加文件名和方法信息
	//Logger.SetReportCaller(true)
}

type LogFileInfo struct {
	Root       string
	Path       string
	Name       string
	Ext        string
	TimeFormat string
}

// 生成存储地址
func (l *LogFileInfo) createSavePath() string {
	return path.Join(l.Root, l.Path, l.Name)
}

// 初始化日志信息
func initLogFileInfo() (logFileInfo *LogFileInfo) {
	logFileInfo = new(LogFileInfo)

	logFileInfo.Root = "runtime/"
	logFileInfo.Path = "logs"
	logFileInfo.Name = "log"
	logFileInfo.Ext = ".log"
	// 精确到毫秒
	logFileInfo.TimeFormat = time.DateTime
	return
}
